using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Mqtt.mqttresponse;
using Admin.NET.Core;
using Furion;
using Mapster;
using Newtonsoft.Json;
using SqlSugar;
using Yitter.IdGenerator;

namespace Admin.NET.Application;

public class TestInsert
{
	public static async void SetInfoAll()
	{
		string[] arr = File.ReadAllLines("d:/1.csv");
		int index = 0;
		SqlSugarRepository<ElectricMeter> _contextold = App.GetService<SqlSugarRepository<ElectricMeter>>();
		SimpleClient<ElectricMeter> _context = _contextold.CopyNew();
		SqlSugarRepository<PowerConsumptionRecord> _contextTwoold = App.GetService<SqlSugarRepository<PowerConsumptionRecord>>();
		_contextTwoold.CopyNew();
		List<ElectricMeter> info = (from u in _context.Context.Queryable<ElectricMeter>()
			where u.CreateUserId == (long?)34527044156869L
			select u).ToList();
		List<PowerConsumptionRecord> list = new List<PowerConsumptionRecord>();
		string[] array = arr;
		foreach (string str in array)
		{
			index++;
			string[] result = str.Split(",");
			DateTime.Parse(result[0]);
			ModelMqttResponse modelMqtt = new ModelMqttResponse
			{
				d = "{\"AAAAAAAAAAAA\":{\"TotalE\":\"" + result[1] + "\",\"Alltotal\":\"" + result[1] + "\",\"VoltageAll\":null,\"CurrentAll\":null,\"ActivePowerAll\":null,\"SharpElectricE\":null,\"PeakElectricE\":null,\"FlatElectricE\":null,\"ValleyElectricE\":null,\"State\":\"0000\"}}",
				o = 5
			};
			Console.WriteLine($"当前数据已更新{index}/{arr.Length} 成功");
			ElectricMeter model = info.Where((ElectricMeter u) => u.Sn == result[2]).FirstOrDefault();
			if (model != null)
			{
				PowerConsumptionRecord powerConsumptionRecord = Analysis(modelMqtt, result[2], "meter", DateTime.Parse(result[0]), model, Convert.ToDecimal(result[3]));
				list.Add(powerConsumptionRecord);
			}
			if (index % 500 == 0 || index == str.Length)
			{
				if (index > 37500)
				{
					await _contextTwoold.InsertRangeAsync(list);
				}
				list.Clear();
			}
		}
	}

	private static decimal ChangeDataToD(string strData)
	{
		decimal dData = default(decimal);
		if (strData.ToLower().Contains("e"))
		{
			decimal d = decimal.Parse(strData, NumberStyles.Float);
			CultureInfo cultureInfo = new CultureInfo("cn");
			decimal.TryParse(strData, NumberStyles.Float, cultureInfo, out dData);
		}
		else
		{
			decimal.TryParse(strData, out dData);
		}
		return dData;
	}

	/// <summary>
	/// 数据处理
	/// </summary>
	/// <param name=" upload"></param>
	/// <param name="powerConsumption"></param>
	private static void DataHandling(UploadMqttInfo upload, PowerConsumptionRecord powerConsumption, decimal multiplier)
	{
		if (!string.IsNullOrEmpty(upload.ActivePowerAll))
		{
			string[] acticePower = upload.ActivePowerAll.Split(',');
			if (acticePower.Length == 4)
			{
				powerConsumption.ActivePowerAll = ChangeDataToD(acticePower[3]) * multiplier;
				powerConsumption.ActivePowerA = ChangeDataToD(acticePower[2]) * multiplier;
				powerConsumption.ActivePowerB = ChangeDataToD(acticePower[1]) * multiplier;
				powerConsumption.ActivePowerC = ChangeDataToD(acticePower[0]) * multiplier;
			}
		}
		if (!string.IsNullOrEmpty(upload.CurrentAll))
		{
			string[] current = upload.CurrentAll.Split(',');
			if (current.Length == 3)
			{
				powerConsumption.CurrentA = ChangeDataToD(current[2]) * multiplier;
				powerConsumption.CurrentB = ChangeDataToD(current[1]) * multiplier;
				powerConsumption.CurrentC = ChangeDataToD(current[0]) * multiplier;
			}
		}
		if (!string.IsNullOrEmpty(upload.VoltageAll))
		{
			string[] voltage = upload.VoltageAll.Split(',');
			if (voltage.Length == 3)
			{
				powerConsumption.VoltageA = ChangeDataToD(voltage[2]);
				powerConsumption.VoltageB = ChangeDataToD(voltage[1]);
				powerConsumption.VoltageC = ChangeDataToD(voltage[0]);
			}
		}
		if (upload.ActivePowerAll == null && upload.VoltageAll == null && upload.CurrentAll == null)
		{
			powerConsumption.IsHands = true;
		}
	}

	private static PowerConsumptionRecord Analysis(ModelMqttResponse modelMqtt, string code, string type, DateTime nowTime, ElectricMeter meterInfo, decimal diff)
	{
		string deviceKey = "AAAAAAAAAAAA";
		PowerConsumptionRecord powerConsumption = null;
		try
		{
			Dictionary<string, UploadMqttInfo> info = JsonConvert.DeserializeObject<Dictionary<string, UploadMqttInfo>>(modelMqtt.d);
			if (meterInfo != null)
			{
				UploadMqttInfo upload = info[deviceKey];
				if (!string.IsNullOrEmpty(upload.State))
				{
					meterInfo.GateStatus = ((upload.State == "0000") ? 1 : 0);
				}
				meterInfo.SignalStatus = 1;
				meterInfo.LatestMeterReadingTime = nowTime;
				string[] total = upload.Alltotal?.Split(',') ?? new string[0];
				if (total.Length != 5)
				{
					total = new string[5] { "0", "0", "0", "0", upload.TotalE };
				}
				decimal multiplier = (decimal)meterInfo.Multiplier;
				upload.TotalE = total[4];
				upload.SharpElectricE = total[3];
				upload.PeakElectricE = total[2];
				upload.FlatElectricE = total[1];
				upload.ValleyElectricE = total[0];
				decimal all = ChangeDataToD(upload.TotalE) * multiplier;
				decimal sharpElectricE = ChangeDataToD(upload.SharpElectricE) * multiplier;
				decimal peakElectricE = ChangeDataToD(upload.PeakElectricE) * multiplier;
				decimal flatElectricE = ChangeDataToD(upload.FlatElectricE) * multiplier;
				decimal valleyElectricE = ChangeDataToD(upload.ValleyElectricE) * multiplier;
				decimal value = all;
				decimal? combinedActiveTotalElectricEnergy = meterInfo.CombinedActiveTotalElectricEnergy;
				decimal totalcheck = ((decimal?)value - combinedActiveTotalElectricEnergy).GetValueOrDefault();
				value = sharpElectricE;
				combinedActiveTotalElectricEnergy = meterInfo.CombinedActiveSharpElectricEnergy;
				decimal sharpElectricEcheck = ((decimal?)value - combinedActiveTotalElectricEnergy).GetValueOrDefault();
				value = peakElectricE;
				combinedActiveTotalElectricEnergy = meterInfo.CombinedActivePeakElectricEnergy;
				decimal peakElectricEcheck = ((decimal?)value - combinedActiveTotalElectricEnergy).GetValueOrDefault();
				value = flatElectricE;
				combinedActiveTotalElectricEnergy = meterInfo.CombinedActiveFlatElectricEnergy;
				decimal flatElectricEcheck = ((decimal?)value - combinedActiveTotalElectricEnergy).GetValueOrDefault();
				value = valleyElectricE;
				combinedActiveTotalElectricEnergy = meterInfo.CombinedActiveValleyElectricEnergy;
				decimal valleyElectricEcheck = ((decimal?)value - combinedActiveTotalElectricEnergy).GetValueOrDefault();
				decimal allfee = default(decimal);
				decimal lossfee = default(decimal);
				if (sharpElectricE > 0m)
				{
					meterInfo.CombinedActiveSharpElectricEnergy = sharpElectricE;
				}
				if (flatElectricE > 0m)
				{
					meterInfo.CombinedActiveFlatElectricEnergy = flatElectricE;
				}
				if (peakElectricE > 0m)
				{
					meterInfo.CombinedActivePeakElectricEnergy = peakElectricE;
				}
				meterInfo.CombinedActiveTotalElectricEnergy = all;
				if (valleyElectricE > 0m)
				{
					meterInfo.CombinedActiveValleyElectricEnergy = valleyElectricE;
				}
				meterInfo.IsRead = true;
				powerConsumption = meterInfo.Adapt<PowerConsumptionRecord>();
				powerConsumption.CreateTime = nowTime;
				powerConsumption.UpdateTime = nowTime;
				if (flatElectricE > 0m)
				{
					powerConsumption.CombinedActiveFlatElectricEnergyDifference = 0m;
				}
				else
				{
					powerConsumption.CombinedActiveFlatElectricEnergy = 0m;
				}
				if (peakElectricE > 0m)
				{
					powerConsumption.CombinedActivePeakElectricEnergyDifference = 0m;
				}
				else
				{
					powerConsumption.CombinedActivePeakElectricEnergy = 0m;
				}
				if (sharpElectricE > 0m)
				{
					powerConsumption.CombinedActiveSharpElectricEnergyDifference = 0m;
				}
				else
				{
					powerConsumption.CombinedActiveSharpElectricEnergy = 0m;
				}
				if (valleyElectricE > 0m)
				{
					powerConsumption.CombinedActiveValleyElectricEnergyDifference = 0m;
				}
				else
				{
					powerConsumption.CombinedActiveValleyElectricEnergy = 0m;
				}
				powerConsumption.CombinedActiveTotalElectricEnergyDifference = diff;
				powerConsumption.MeterId = meterInfo.Id;
			}
			powerConsumption.Price = -1;
			powerConsumption.FlatPrice = -1;
			powerConsumption.ValleyPrice = -1;
			powerConsumption.PeakPrice = -1;
			powerConsumption.SharpPrice = -1;
			powerConsumption.Type = -1;
			powerConsumption.Amount = default(decimal);
			powerConsumption.Id = YitIdHelper.NextId();
			powerConsumption.IsDelete = false;
			powerConsumption.LossAmount = default(decimal);
			powerConsumption.RoomId = meterInfo.RoomId;
			powerConsumption.BuildingId = meterInfo.BuildingId;
			powerConsumption.IsDelete = false;
			powerConsumption.ElectricityLossPercentage = 0.0;
		}
		catch (Exception)
		{
		}
		return powerConsumption;
	}
}
